package com.icloud.admin.domain;

import com.icloud.framework.domain.model.AuditingEntity;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;

import javax.persistence.*;
import java.util.HashSet;
import java.util.Set;

@Entity(name = "sys_roles")
@EntityListeners(AuditingEntityListener.class)
public class Role extends AuditingEntity {
    private String name;
    private boolean enabled;
    private String description;

    @ManyToMany(cascade = CascadeType.PERSIST, fetch = FetchType.LAZY)
    @JoinTable(name = "sys_role_menu_relation",
            joinColumns = {@JoinColumn(name = "role_id", referencedColumnName = "id")},
            inverseJoinColumns = {@JoinColumn(name = "menu_id", referencedColumnName = "id")})
    private Set<Menu> menus = new HashSet();

    @ManyToMany(cascade = CascadeType.PERSIST, fetch = FetchType.LAZY)
    @JoinTable(name = "sys_role_resource_relation",
            joinColumns = {@JoinColumn(name = "role_id", referencedColumnName = "id")},
            inverseJoinColumns = {@JoinColumn(name = "resource_id", referencedColumnName = "id")})
    private Set<Resource> resources = new HashSet();


    public Role() {
    }

    public Role(String name, String description) {
        setName(name);
        this.enabled = true;
        this.description = description;
    }

    public void changeProps(String name, String description) {
        setName(name);
        this.description = description;
    }

    public void disable() {
        this.enabled = false;
    }

    /**
     * 分配菜单
     *
     * @param menu
     */
    public void assignMenu(Menu menu) {
        if (menu != null) {
            if (menu.getParent() != null) {
                this.assignMenu(menu.getParent());
            }
            this.menus.add(menu);
        }
    }

    /**
     * 撤销菜单
     *
     * @param menu
     */
    public void undoAssignedMenu(Menu menu) {
        this.menus.remove(menu);
    }

    public void undoAssignedAllMenu() {
        this.menus = new HashSet<Menu>();
    }

    /**
     * 分配资源
     *
     * @param resource 资源
     */
    public void assignResource(Resource resource) {
        this.resources.add(resource);

    }

    /**
     * 撤销资源
     *
     * @param resource 资源
     */
    public void undoAssignedResource(Resource resource) {
        this.resources.remove(resource);
    }

    public void undoAssignedAllResource() {
        this.resources = new HashSet();
    }


    protected void setName(String name) {
    /*    this.assertArgumentNotEmpty(name, "角色名称必填");*/
        this.name = name;
    }


}
